package controllayer;

import java.sql.SQLException;
import java.util.ArrayList;

import dblayer.*;
import modellayer.Supplier;
import modellayer.Product;
import modellayer.SalesOrder;

public class ProductCtr {
	
	private DBProduct dbProduct;
	private DBSupplier dbSupplier;
	
	public ProductCtr()
	{
		dbProduct = new DBProduct();
		dbSupplier = new DBSupplier();
	}
	
	/**
	 * 
	 * @param productID
	 * @return
	 * @throws SQLException
	 */
	public Product findProduct(int productID) throws SQLException
	{
		return dbProduct.selectSingleProduct(productID, true);
	}
	
	/**
	 * 
	 * @return
	 * @throws SQLException
	 */
	private ArrayList<Product> allProducts() throws SQLException
	{
		return dbProduct.getAllProducts(true);
	}
	
	/**
     * Adds all products objects to a two dimensional array so they can be used in a JTable in NewOrderPanel
     * @return array data[][]
	 * @throws SQLException 
     */
    public String[][] productToTableArray(String searchString) throws SQLException
    {
       ArrayList<Product> productList = allProducts();
       ArrayList<Supplier> supplierList = dbSupplier.getAllSuppliers();
    	
       int index = 0; 
       int arrayIndex = 0;
       String data[][] = new String[productList.size()][5];
       
       if(searchString.equals(""))
       {
    	   while(index < productList.size())
    	   {
    		   Product product = productList.get(index);
	    	   data[index][0] = Integer.toString(product.getProductID());
	           data[index][1] = product.getName();
	           data[index][2] = Integer.toString(product.getSalesPrice());
	           data[index][3] = product.getProductType();
	           data[index][4] = Integer.toString(product.getInStock());
	           index++;
    	   }           
       } else {
	       while(index < productList.size())
	       {
	    	   Product product = productList.get(index);
    		   if(product.getSupplier().getName().equals(searchString))
    		   		{
			    	   data[arrayIndex][0] = Integer.toString(product.getProductID());
			           data[arrayIndex][1] = product.getName();
			           data[arrayIndex][2] = Integer.toString(product.getSalesPrice());
			           data[arrayIndex][3] = product.getProductType();
			           data[arrayIndex][4] = Integer.toString(product.getInStock());
			           arrayIndex++;
    		   		}
	           index++;
	       }
       }
       return data;
    }
}
